<?php
#require_once('TVB/pms/pdes/common/util/ArrayDiff.class.php');

class P_ProgrammeGetAction extends BaseAction 
{
	public $id;
	public $type;
	public $step;
	public $act;
	public $unpublish;
	public $error_code;

	public $ut;
	public $from;

    public function execute()
    {
		if(!is_null($this->error_code))
		{
			$this->addError('Programme.Proof read', array($this->error_code, 'Programme.Proof read'));	
		}

		try
		{
			# add publish log
			$this->setData("publishLog", publish_log::getPublishLog('programme', $this->id));
            $this->setData('special_operation_premium', TRUE);

			if(!empty($this->unpublish)) {Model::$dbo['r'] = CommonUtils::getDbConn(0,'preview');}

			//highlight field
			if (empty($this->unpublish)) {$this->highlight("programme", $this->id, $this->act);}

			//programme detail 
			$programme = new p_programme();
			$programme_detail = $programme->getDetails($this->id);
			//handle multiple language
			$programme_name = explode("\n\t",$programme_detail->mix_programme_name);
			$programme_detail->zh_programme_name = isset($programme_name[0]) ? $programme_name[0] : '';
			$programme_detail->en_programme_name = isset($programme_name[1]) ? $programme_name[1] : '';
			$settop_box_name = explode("\n\t", $programme_detail->mix_settop_box_name);
			$programme_detail->zh_settop_box_name = isset($settop_box_name[0]) ? $settop_box_name[0] : '';
			$programme_detail->en_settop_box_name = isset($settop_box_name[1]) ? $settop_box_name[1] : '';
			$programme_detail->nominal_duration = !is_null($programme_detail->nominal_duration) ? CommonUtils::sec_to_num($programme_detail->nominal_duration) : array('','','');
			$programme_detail->number_of_episodes = ($programme_detail->number_of_episodes != 0) ? $programme_detail->number_of_episodes : '';
			$programme_detail->starting_original_episode_no = ($programme_detail->starting_original_episode_no != 0) ? $programme_detail->starting_original_episode_no : '';
			$programme_detail->average_rating = ($programme_detail->average_rating != 0) ? $programme_detail->average_rating : '';
			$programme_detail->forum_id = ($programme_detail->forum_id != 0) ? $programme_detail->forum_id : '';
			$programme_detail->production_start_date = ($programme_detail->production_start_date != '0000-00-00 00:00:00') ? substr($programme_detail->production_start_date,0,10) : '';
			$programme_detail->production_end_date   = ($programme_detail->production_end_date != '0000-00-00 00:00:00') ? substr($programme_detail->production_end_date,0,10) : '';

			$programme_detail->publish_datetime = is_null($programme_detail->publish_datetime) || $programme_detail->publish_datetime == "0000-00-00 00:00:00" ? CommonUtils::formatDate(date('Y-m-d H:i:s',time())) : CommonUtils::formatDate($programme_detail->publish_datetime);

			$programme_detail->expire_datetime  = is_null($programme_detail->expire_datetime) || $programme_detail->expire_datetime == "0000-00-00 00:00:00" ?  CommonUtils::formatDate("2029-12-31 23:59:59") : CommonUtils::formatDate($programme_detail->expire_datetime);

			$programme_detail->first_time_onair = CommonUtils::formatDate($programme_detail->first_time_onair);
			$programme_detail->first_episode_time_onair = CommonUtils::formatDate($programme_detail->first_episode_time_onair);
			$programme_detail->last_episode_time_onair = CommonUtils::formatDate($programme_detail->last_episode_time_onair);
			$this->setData("programme", $programme_detail);

            $this->__init_country_list();
            
            $premium_list = $this->__init_programme_premium();
            $this->__init_programme_subscription();
            $this->__init_programme_ppv();

			//company code list
			$company_code = new company_code();
			$company_code_list = $company_code->get();
			$company_code_option = "";
			foreach ($company_code_list as $company_code)
			{
				$selected = ($company_code->code == AC::DEFAULT_COMPANY_CODE) ? "selected='selected'" : '';
				$company_code_option .= '<option value='.$company_code->code.' '.$selected.'>'.$company_code->system_label.'</option>';
			}
			$this->setData("company_code_option", $company_code_option);

			//cpl category list
			$category_list = array();
			if(!empty($programme_detail->cpl_category_id))
			{
				$cpl_category = new cpl_category();
				//parent or child
				if ($cpl_category->IsParent($programme_detail->cpl_category_id))
				{
					$category_detail->parent_id = $programme_detail->cpl_category_id;
					$category_detail->id = '';
					$sub_categorys = $cpl_category->getSubCategorys($programme_detail->cpl_category_id);
					$category_list[0] = 'Please Select...'; 
					foreach ($sub_categorys as $cat_id => $cat_name)
					{
						$category_list[$cat_id] = $cat_name;
					}
					$this->setData("category_detail", $category_detail);
				}
				else
				{
					$category_detail = $cpl_category->getCategoryByID($programme_detail->cpl_category_id);
					$category_list[0] = 'Please Select...'; 
					$sub_categorys = $cpl_category->getSubCategorys($category_detail[0]->parent_id);
					foreach ($sub_categorys as $cat_id => $cat_name)
					{
						$category_list[$cat_id] = $cat_name;
					}

					$this->setData("category_detail", $category_detail[0]);
				}
				$this->setData("category_list", $category_list);
			}
			else
			{
				$category_detail->parent_id = '';
				$category_detail->id = '';
				$this->setData("category_detail", $category_detail);
				$category_list[0] = 'Please Select...'; 
				$this->setData("category_list", $category_list);
			}

			//tvb category list
			$tvb_category_list = array();
			$programme_tvbcom_category = new p_programme_tvbcom_category();
			$tvb_category_list = $programme_tvbcom_category->getCategoryByProgrammeID($this->id);
			$tvb_category_arr = array();
			foreach($tvb_category_list as $tvb_category)
			{
				$parent_name = tvbcom_category::getParentName($tvb_category->system_label, $tvb_category->parent_id);
				$tvb_category_arr[] = array("id"=>$tvb_category->category_id, "system_label"=>$parent_name." ".$tvb_category->system_label);
			}
			$this->setData("tvb_category_list", $tvb_category_arr);

			//tag list
			$tag_list = array();
			if (!empty($programme_detail->tags))
			{
				$tag = new p_tag();
				$tag_all = $tag->getTagList($programme_detail->tags);
				foreach ($tag_all as $tag)
				{
					$tag_list[$tag->typeid][] = array("id"=>$tag->id,"system_label"=>$tag->system_label);
				}
			}

			//alow tag
			$allow_tag = CommonUtils::get_allow_tags("programme");
			$tag_type = new tag_type();
			$allow_tag_list = $tag_type->findByInSql($allow_tag);
			$tag_arr = array();
			foreach ($allow_tag_list as $tag)
			{
				$tag_arr[$tag->id] = array("id"=>$tag->id,"name"=>$tag->system_label,'restrict'=>$tag->restricted);
				//when add
				if (empty($programme_detail->tags))
				{
					$tag_list[$tag->id] = array();
				}
			}
			$this->setData("allow_tag", $tag_arr);
			$this->setData("tag_list", $tag_list);

			// modified by vanni at 2010-04-06 for bug:3686
			// image/video folder list
			$image_folder_list = array();
			$image_folders = array();
			if (!empty($programme_detail->folders))
            {
                $folder = new p_folder();
                $all_folder = $folder->findByInSql($programme_detail->folders);

				$is_published = CommonUtils::is_published('programme',$this->id);
                $video_folders = $image_folders = array();
				foreach ($all_folder as $single_folder)
				{
					$folders = array(
						'fid' => $single_folder['id'],
						'fspec'	=> $single_folder['folder_type_id'],
						'total'	=> $single_folder['total'],
						'ftype'	=> $single_folder['folder_item_type_id'],
                        'path' => $single_folder['path'],
						'fname'	=> htmlentities($single_folder['system_label'], ENT_QUOTES, 'UTF-8'),
						'premium' => $premium_list, 
					);

					if ($single_folder['folder_item_type_id'] == AC::FOLDER_TYPE_IMAGE)
					{
						$item_list = $folder->get_folder_items($single_folder['id']);
						if (!empty($item_list))
						{
							foreach ($item_list as &$item)
							{
								$item['title']  = 'ID:'.$item['id'].'<br />' 
									. htmlentities($item['title'], ENT_QUOTES, 'UTF-8');
								$item['status'] = '';
								$item['flag']   = p_episode_video::getEpisodeID($item['id']);
							}
						}
						$folders['items'] = $item_list;
						$image_folders[]  = $folders;
					}elseif ($single_folder['folder_item_type_id'] == AC::FOLDER_TYPE_VIDEO){
						$video_folders[]  = $folders;
					}
				}
				$video_folder_list = array('pid'=>$programme_detail->id,'ptype'=>'programme','folders'=>$video_folders);
				$image_folder_list = array('pid'=>$programme_detail->id,'ptype'=>'programme','folders'=>$image_folders);
			}
			$this->setData("video_folder_list", $video_folder_list);
			$this->setData("image_folder_list", $image_folder_list);

			/**
			// image/video folder list
			$video_folder_list = array();
			$image_folder_list = array();
			$video_folders = array();
			$image_folders = array();
			if (!empty($programme_detail->folders))
			{
				$folder = new folder();
				$all_folder = $folder->findByInSql($programme_detail->folders);

				$is_published = CommonUtils::is_published('programme',$this->id);
				$diff = isset($this->_data['diff_folder']) ? $this->_data['diff_folder'] : array();
				foreach ($all_folder as $single_folder)
				{

					if ($this->act == 'view' && !$this->unpublish)
					{
						$folders = CommonUtils::getDiffFolderItem($single_folder,$this->act,$diff, $this->unpublish,$is_published);
					}
					else
					{
						$item_list = $folder->get_folder_items($single_folder['id']);
						if (!empty($item_list))
						{
							foreach ($item_list as &$item)
							{
								$item['title']  = 'ID:'.$item['id'].'<br />' 
												  . htmlentities($item['title'], ENT_QUOTES, 'UTF-8');
								$item['status'] = '';
								$item['flag']   = episode_video::getEpisodeID($item['id']);
							}
						}
						$folders = array(
										'fid'	=> $single_folder['id'],
										'fspec'	=> $single_folder['folder_type_id'],
										'total'	=> $single_folder['total'],
										'ftype'	=> $single_folder['folder_item_type_id'],
										'fname'	=> htmlentities($single_folder['system_label'], ENT_QUOTES, 'UTF-8'),
										'items'	=> $item_list
									);
					}

					if ($single_folder['folder_item_type_id'] == AC::FOLDER_TYPE_VIDEO)
					{
						$video_folders[] = $folders;
					}
					elseif ($single_folder['folder_item_type_id'] == AC::FOLDER_TYPE_IMAGE)
					{
						$image_folders[] = $folders;
					}
				}
				$video_folder_list = array('pid'=>$programme_detail->id,'ptype'=>'programme','folders'=>$video_folders);
				$image_folder_list = array('pid'=>$programme_detail->id,'ptype'=>'programme','folders'=>$image_folders);
			}
			$this->setData("video_folder_list", $video_folder_list);
			$this->setData("image_folder_list", $image_folder_list);
			 */

			//network code list
			$network_code_list = array();
			$network_code = new network_code();
			if (!empty($programme_detail->first_network_codes))
			{
				$check_code_list = explode(",", $programme_detail->first_network_codes);
			}
			$code_list = $network_code->getCodeByLang(language::getLanguageID(AC::DEFAULT_LANGUAGE));
			if (!empty($code_list))
			{
				foreach ($code_list as $code)
				{
					$checked = (!empty($check_code_list) && in_array($code->code,$check_code_list)) ? 1 : 0;
					$network_code_list[] = array('value'=>$code->code,'label'=>$code->title, 'checked'=>$checked);
				}
			}
			$this->setData("code_list", $network_code_list);
			//programme cpl category list
			$programme_cpl = new p_programme_cpl();
			$cpl_list = $programme_cpl->getCplByProgrammeID($this->id);
			$this->setData("cpl_list", $cpl_list);
			//$this->setData("cpl_data", $this->getCplData($cpl_list[0]));

			//cast role list 
			$cast_role = new cast_role();
			if ($programme_detail->highlighted_cast_roles != '')
			{
				$cast_role_list = $cast_role->findByInSql($programme_detail->highlighted_cast_roles, AC::ROLE_TYPE_CAST);
			}
			else
			{
				$cast_role_list = array();
			}
			$cast_role_id = array();
			$arr_cast = array();
			if (!empty($cast_role_list))
			{
				foreach ($cast_role_list as $cast)
				{
					$cast_role_id[] = $cast->id;
					$arr_cast[$cast->id] = $cast->system_label;
				}
			}
			//crew role list
			if ($programme_detail->highlighted_cast_roles != '')
			{
				$crew_role_list = $cast_role->findByInSql($programme_detail->highlighted_cast_roles, AC::ROLE_TYPE_CREW);
			}
			else
			{
				$crew_role_list = array();
			}
			$crew_role_id = array();
			$arr_crew = array();
			if (!empty($crew_role_list))
			{
				foreach ($crew_role_list as $crew)
				{
					$crew_role_id[] = $crew->id;
					$arr_crew[$crew->id] = $crew->system_label;
				}
			}
			$this->setData("arr_cast", $arr_cast);	
			$this->setData("arr_crew", $arr_crew);	

			$this->handle_cast_crew($cast_role_id, $crew_role_id);
			//$this->handle_cast_crew($cast_role_id, $crew_role_id, "remote");
		/*
		if (!empty($this->_data['publishLog']))
		{
			$this->cast_highlight($cast_role_id, $crew_role_id);
		}
		 */
			//common
			$this->setData("id", $this->id);
			$this->setData("type", $this->type);
			$this->setData('from', $this->from);
			$this->setData("step", $this->step);
			$this->setData("act", $this->act);
			$this->setData("unpublish", $this->unpublish);

			$this->make_diff('programme', $this->id, $this->act, $programme_detail);

			return 'succ';
		}
		catch(Exception $e)
		{
			error_log("programme get: {$this->id}" . var_export($e,1));

			$this->emptyData();
			return 'system-error';
		}
	}    

    private function __init_programme_premium()
    {
        $premium = new p_programme_premium();
        $premium_data = $premium->get($this->id);
        $premium_data = Model::object2array($premium_data);
        if(empty($premium_data)) {
            $premium_ret = array(
                'premium_title'    => '',
                'premium_title_en'     => '',
                'premium_auto_publish'      => 0, 
                'premium_items' => array('subscription'=>0,'ppv'=>0) 
            );
			$return = '';
        }
        else
        {
            $premium_ret = array(
                'premium_title'=> $premium_data['title_zh'],
                'premium_title_en'=> $premium_data['title_en'],
                'premium_auto_publish'=> $premium_data['auto_publish'],
                'premium_items' => array('subscription'=>$premium_data['subscription_flag'],'ppv'=>$premium_data['ppv_flag'])
            ) ;

			$premium_arr = array();

			if (!empty($premium_data['subscription_flag'])) {
				$premium_arr[] = 'subscription';
			}

			if (!empty($premium_data['ppv_flag'])) {
				$premium_arr[] = 'ppv';
			}

			$return = implode(',', $premium_arr);
        }

        $this->setData('programme_premium', $premium_ret);

		return $return;
    }
	/**
	 * highlight modify field
	 */
	public function make_diff($type, $id, $act, $programme)
	{
		/*
		if ($act == 'view')
		{
			$diff = $this->_data['diff_other'];
			$highlight = $diff['programme'][$id];
			$highlight['zh_programme_name'] = $diff['programme-language'][$id.'1']['title'];
			$highlight['en_programme_name'] = $diff['programme-language'][$id.'2']['title'];
			$highlight['zh_settop_box_name'] = $diff['programme-language'][$id.'1']['settop_box_name'];
			$highlight['en_settop_box_name'] = $diff['programme-language'][$id.'2']['settop_box_name'];
			$highlight = array_merge($highlight, $diff['programme-language'][$id.'1']);
			$this->setData('programme_diff', $highlight);
		}
		elseif ($act == 'edit' || $act == 'add')
		{
			$diff = array_fill_keys(array_keys(Model::object2array($programme)), false);
			$this->setData("programme_diff", $diff);
		}
		 */

		$diff = array_fill_keys(array_keys(Model::object2array($programme)), false);
		$this->setData("programme_diff", $diff);
	}

	/**
	 * highlight init handle
	 */
	public function highlight($type, $id, $act)
	{
		// modified by vanni at 2010-04-06 for bug:3686
		return true;

		$db_local =  CommonUtils::getDbConn()->getDbHandle();
		$db_remote =  CommonUtils::getDbConn(0, 'preview')->getDbHandle();

		$proof = new ProofreadSend();
		$local_arr = $proof->getProofreadData($db_local, $type, $id); 
		$remote_arr = $proof->getProofreadData($db_remote, $type, $id); 
		$diff_folder = ArrayDiff::multi_diff($local_arr, $remote_arr);
		#echo "<!-- ";
		#echo "====\n Local Data:\n";
		#print_r($local_arr);
		#echo "====\n Remote Data:\n";
		#print_r($remote_arr);
		#echo "====\n Diff Result Data:\n";
		#print_r($diff_folder);
		#echo " -->";

		if ($act == 'view')
		{
			$diff_other = ArrayDiff::array_diff($local_arr, $remote_arr, $diff_other);
			$this->setData("diff_other", $diff_other);
		}
		/*
		$remote_casts = isset($remote_arr['programme'][0]) ? $remote_arr['programme'][0]['casts'] : json_encode(array());
		$this->setData('remote_casts', $remote_casts);
		 */
		$this->setData("diff_folder", $diff_folder);
	}

	/**
	 * handle cast/crew data
	 */
	public function handle_cast_crew($cast_role_id, $crew_role_id, $type="")
	{
		$json_cast_list = array();
		if ($type == 'remote')
		{
			$json_cast_list = json_decode($this->_data['remote_casts'], true);
		}
		else
		{
			$json_cast_list = json_decode($this->_data['programme']->casts, true);
		}

		$cast_list = array();
		$crew_list = array();
		if (!empty($json_cast_list))
		{
			foreach ($json_cast_list as $role_id=>$list)
			{
				if (in_array($role_id, $cast_role_id))
				{
					$cast_list[$role_id] = $list;
				}
				elseif (in_array($role_id, $crew_role_id))
				{
					$crew_list[$role_id] = $list;
				}
			}
		}
		else
		{
			$cast_list = array();
			$crew_list = array();
		}

		$this->setData($type."cast_list", $cast_list);
		$this->setData($type."crew_list", $crew_list);
	}

	/**
	 * highlight cast/crew data
	 */
	public function cast_highlight($cast_role_id, $crew_role_id)
	{
		$cast_list = $this->_data['cast_list'];
		$crew_list = $this->_data['crew_list'];
		$remote_cast_list = $this->_data['remotecast_list'];
		$remote_crew_list = $this->_data['remotecrew_list'];

		$highlight_cast = array();
		$highlight_crew = array();
		if (!empty($cast_list) )
		{
			$this->compare_cast_crew($cast_list, $remote_cast_list, $cast_role_id, 'cast');
		}
		if (!empty($crew_list))
		{
			$this->compare_cast_crew($crew_list, $remote_crew_list, $crew_role_id, 'crew');
		}
	}

	/**
	 * compare cast/crew data
	 */
	public function compare_cast_crew($cast_list, $remote_cast_list, $cast_role_id, $type)
	{
		$h_object = "highlight_".$type;
		$compare_data = array();
		foreach ($cast_role_id as $role_id)
		{
			//add
			if (isset($cast_list[$role_id]) && !isset($remote_cast_list[$role_id])) 
			{
				$compare_data[$role_id] = true;
			}
			elseif  (isset($cast_list[$role_id]) && isset($remote_cast_list[$role_id])) 
			{
				//modify
				$i = 0;
				$cast_flag = false;
				foreach ($cast_list[$role_id] as $cast_value)
				{
					if (!isset($remote_cast_list[$role_id][$i])) continue;
					$diff_cast = array_diff_assoc($cast_list[$role_id][$i], $remote_cast_list[$role_id][$i]);
					if (!empty($diff_cast))
					{
						$cast_flag = true;
						break;
					}
					$i++;
				}
			
				$compare_data[$role_id] = $cast_flag;
			}
			else
			{
				$compare_data[$role_id] = false;
			}
		}
		$this->setData($h_object, $compare_data);
	}

    private function __init_programme_ppv()
    {
        $programme_ppv = new p_programme_ppv;
        $ppv = $programme_ppv->get($this->id);
        $ppv = Model::object2array($ppv);
        if (empty($ppv)) {
            $ppv_ret = array(
                'publish_datetime'      => '0000-00-00 00:00:00', 
                'expire_datetime'       => '0000-00-00 00:00:00', 
                'ppv_country'=>'',
                'ppv_country_allow_deny'=> '',
            );
        }
        else 
        {
            if('ALL' == $ppv['country_allow_list'])
            {
                $deny_flag = 1; 
                $country = $ppv['country_deny_list'];
            }
            else
            {
                $deny_flag = 0;
                $country = $ppv['country_allow_list'];
            }

            $ppv_ret = array(
                'publish_datetime'      => $ppv['publish_datetime'], 
                'expire_datetime'       => $ppv['expire_datetime'], 
                'ppv_country'=> $country,
                'ppv_country_allow_deny'=> $deny_flag
            );
        }
        $this->setData('programme_ppv', $ppv_ret);
    }
    private function __init_programme_subscription()
    {
        $programme_subscription = new p_programme_subscription;
        $subscription = $programme_subscription->get($this->id);
        $subscription = Model::object2array($subscription);
        if (empty($subscription)) {
            $subscription_ret = array(
                'publish_datetime'      => '0000-00-00 00:00:00', 
                'expire_datetime'       => '0000-00-00 00:00:00', 
                'free'=>0,
                'subscription_country'=> '',
                'subscription_country_allow_deny'=> ''
            );
        }
        else 
        {
            if('ALL' == $subscription['country_allow_list'])
            {
                $deny_flag = 1; 
                $country = $subscription['country_deny_list'];
            }
            else
            {
                $deny_flag = 0;
                $country = $subscription['country_allow_list'];
            }
            $subscription_ret = array(
                'publish_datetime'      => $subscription['publish_datetime'], 
                'expire_datetime'       => $subscription['expire_datetime'], 
                'free'=>$subscription['free_flag'],
                'subscription_country'=> $country,
                'subscription_country_allow_deny'=> $deny_flag
            );
        }
        $this->setData('programme_subscription', $subscription_ret);
    }

    private function __init_country_list()
    {
		$country = new country();
        $this->setData('country', $country->getCountryList());
    }
}
?>
